<?php

namespace app\index\controller;

use think\Controller;

use \express\AliKdSearch;
use \payment\Weixin;

use app\index\model\Order;
use app\index\model\Member;
use app\index\model\Award;
use app\index\model\Payorder;
use app\index\model\Express;

class Services extends Controller
{
    public function onsiteService(){
        return view('onsite-service');
    }
    
    public function qrcodePay(){
        $memb = Member::find(session('user.id'));
        return view('qrcode-pay', ['balance' => $memb->memb_balance, 'point' => $memb->memb_point]);
    }
    // 检测是否设置支付密码
    public function checkPaypwd(){
        $pass = Member::where('memb_id', session('user.id'))->value('memb_pay_pass');
        if(empty($pass)) return json(mesg(600, '支付密码未设置，请先设置支付密码'));
        return json(mesg(0, 'set'));
    }
    /**
     * 余额支付
     */
     public function balancePay(){
        $info = input('post.');
        $pass = Member::where('memb_id', session('user.id'))->value('memb_pay_pass');
        if(password_verify($info['paypwd'], $pass)){
            $orderNo = $info['orderNum'];
            $des = $info['describe'];
            $kd = new Express();
            $kdcodes = $kd->getColumn('billcode');  
            $price = count($kdcodes);
            if($price > Member::where('memb_id', session('user.id'))->value('memb_balance')){
                return json(mesg(601, '余额不足,请充值'));
            }
            cache($orderNo, json_encode($kdcodes), 600);
            $order = new Payorder();
            $data = [
                'uid'         => session('user.id'),
                'trade_no'    => $orderNo,
                'des'         => $des,
                'price'       => $price,
                'trade_type'  => 'Balance',
                'status'      => 1,
            ];
            $dataRes = $order->newOrder($data);

            if(!$dataRes) return json(mesg(-1, 'fail'));
            return json(mesg(0, '验证成功'));
        }else{
            return json(mesg(-1,'支付密码错误'));
        }
    }

    //获取快递
    public function getExpress(){
        $express = new Express();
        $kd = $express->getColumn('content');
        return json(mesg(0, 'success', ['data'=>$kd, 'count'=>count($kd)]));
    }

    public function sendBy3(){
        $tag = 'true';
        $memb = Member::get(session('user.id'));
        if($memb->memb_point < 5){
            $tag = 'false';
        }
        return view('send-by3', ['canOrder'=>$tag, 'balance'=>$memb->memb_balance]);
    }
    // 2元寄件接口
    public function newSendOrder($wx = false){
        $data = input('post.');
        $result = $this->validate($data, 'app\index\validate\SendOrderByThree');
        if($result !== true) return json(mesg(-1, $result));
        //2元收费
        $price = 2;
        if($wx){//微信支付
            $weixing = new Weixin;
            $res = $weixing->unifiedOrder($data['describe'], $data['orderNum'], $price, session('openid'));
            if($res){
                $order = new Payorder();
                $data = [
                    'uid'         => session('user.id'),
                    'trade_no'    => $data['orderNum'],
                    'des'         => $data['describe'],
                    'price'       => $price,
                    'trade_type'  => 'JSAPI',
                ];
                $dataRes = $order->newOrder($data);

                if(!$dataRes) return json(mesg(-1, 'fail'));
                //签名数据
                $config = [
                    'appId'     => $res['appid'],     //公众号名称，由商户传入  
                    'timeStamp' => strval(time()),        //时间戳，自1970年以来的秒数     
                    'nonceStr'  => getNonceStr(), //随机串     
                    'package'   => 'prepay_id=' . $res['prepay_id'],     
                    'signType'  => 'MD5',         //微信签名方式
                ];
                $config['paySign'] = $weixing->MakeSign($config); //微信签名 
                return json(mesg(0, 'success', $config));
            }else{
                return json(mesg(-1, '新建订单失败'));
            }    
        }else {//余额支付
            $pass = Member::where('memb_id', session('user.id'))->value('memb_pay_pass');
            if(password_verify($data['paypwd'], $pass)){
                if($price > Member::where('memb_id', session('user.id'))->value('memb_balance')){
                    return json(mesg(601, '余额不足'));
                }
                $order = new Payorder();
                $data = [
                    'uid'         => session('user.id'),
                    'trade_no'    => $data['orderNum'],
                    'des'         => $data['describe'],
                    'price'       => $price,
                    'trade_type'  => 'Balance',
                    'status'      => 1,
                ];
                $dataRes = $order->newOrder($data);

                if(!$dataRes) return json(mesg(-1, 'fail'));
                return json(mesg(0, '验证成功'));
            }else{
                return json(mesg(-1,'支付密码错误'));
            }
        }
    }

    //2元支付成功查询
    public function sendOrderBy3(){
        $tag = false;
        $data = input('post.');
        $result = $this->validate($data, 'app\index\validate\SendOrder');

        if($result !== true) return json(mesg(-1, $result));

        $order = Payorder::where('trade_no', $data['orderNum'])->find();
        if(!empty($order)){
            if($order->status == 1){
                if($order->trade_type == 'Balance'){
                    Member::updateBalance(session('user.id'), -$order->price, $order->des);
                }
                $tag = true;
            }else{
                $wx = new Weixin();
                $res = $wx->queryOrder($data['orderNum']);
                if($res){
                    $order->status = 1;
                    $order->save();
                    $tag = true;
                }
            }
        }
        if($tag){
            sendMessage($order->trade_no);
            Member::updatePoint(session('user.id'), $order->des, -5);
            return json(mesg(0, 'ok'));
        }else{
            return json(mesg(-3, '未支付'));
        }
    }

    public function send(){
        return view('send');
    }
    
    // 新增订单
    public function sendOrder($tag = false){
        if($tag){
            $point = Member::where('memb_id', session('user.id'))->value('memb_point');
            if($point < 5) return json(mesg(-1, '不满足使用条件'));
        }
        $nesField = ['express','sender_info','receiver_info','send_way'];
        $data = request()->only($nesField, 'post');
        $data['orderNum'] = randOrder('S');
        $result = $this->validate($data, 'app\index\validate\SendOrder');
        if($result !== true) return mesg(-1, $result);
        $pktime = input('post.time', null);
        $order = new Order;
        $order->orde_o_code         = $data['orderNum'];
        $order->orde_sender_info    = $data['sender_info'];
        $order->orde_receiver_info  = $data['receiver_info'];
        $order->orde_express        = $data['express'];
        $order->orde_mailType       = $data['send_way'];
        if(!empty($pktime)){
            $order->orde_pickupTime = $pktime;
        }
        $order->orde_uid            = session('user.id');
        $res = $order->save($data);
        sendMessage($order->orde_o_code);
        if($res) {
            return json([
                'code'  => 0,
                'msg'   => '保存成功',
            ]);
        }
    }

    // 充值/提现金额
    public function editMoney($forwhat = false){
        // if($forwhat)
        //     return view('recharge', ['title'=>'申请提现', 'ftitle'=>'提现', 'recharge' => false]);
        // else 
            return view('recharge', ['recharge' => true]);
    }

    //提现申请
    public function withdraw(){
        $paycode = input('paypwd');
        $money = intval(input('money'));
        $user = Member::find(session('user.id'));
        if($paycode == $user->memb_pay_pass){
            if($user->memb_balance < $money){
                return json(mesg('-1', '提现金额大于余额'));
            }
            db('withdraw')->insert([
                'billcode'  => randOrder(),
                'account'   => session('user.id'),
                'price'     => $money
            ]);
            $user->memb_balance -= $money;
            return json(msg(0,'','提现申请已提交'));
        }
        return json(msg(-1, '', '支付密码不正确'));
    }

    //充值金额
    // public function recharge(){
    //     $money = request()->post('recharge_amount');
    //     $user = Member::find(session('user.id'));
    //     $user->memb_balance += $money;
    //     $user->save();
    // }

    //是否支付成功
    public function recharge(){
        $orderNo = input('orderNum', 0);
        $order = Payorder::where('trade_no', $orderNo)->where('uid', session('user.id'))->find();
        if(!empty($order)){
            if($order->status == 1){
                Member::updateBalance(session('user.id'), $order->price, $order->des);
                Member::updateCount(session('user.id'), 1);
                return json(['code'=>0, 'msg'=>'充值成功']);
            }else{
                $wx = new Weixin();
                $res = $wx->queryOrder($orderNo);
                if($res){
                    Member::updateBalance(session('user.id'), $order->price, $order->des);
                    $order->status = 1;
                    $order->save();
                    Member::updateCount(session('user.id'), 1);
                    return json(['code'=>0, 'msg'=>'充值成功']);
                }
            }
            return json(['code'=>-3, 'msg'=>'未支付']);
        }else{
            throw new \Exception('无此订单');
        }
    }

    // 中奖
    public function award(){
        $awname = request()->param('name');
        if(!empty($awname)){
            $award = new Award;
            $award->awar_name    = $awname;
            $award->awar_uid     = session('user.id');
            $award->awar_time    = date('Y-m-d H:i:s');
            $award->awar_type    = 1;
            if($award->save())
                return json(['code'=>0, 'msg'=>'记录成功']);
            else
                return json(['code'=>1, 'msg'=>'记录失败']);
        }
    }

    //快递查询
    public function logistics(){
        $kdCode = request()->post('orderNO');
        if(!empty($kdCode)){
            return AliKdSearch::kdSearch($kdCode);
        }else{
            return null;
        }
    }
}
